package com.lesso.yjy.sunflower.core.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;

public class YearPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        // 将Timestamp转换为LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(preciseShardingValue.getValue().getTime()), ZoneId.systemDefault());

        int year = localDateTime.getYear();
        String targetTableName = "dat_attendance_record_" + year;

        // 检查目标表是否在可用表列表中
        for (String tableName : collection) {
            if (tableName.equals(targetTableName)) {
                return targetTableName;
            }
        }

        // 如果找不到对应年份的表，抛出异常
        throw new IllegalArgumentException("找不到年份 " + year + " 对应的分表: " + targetTableName);
    }
}
